package com.app.newiptv.activity;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.app.newiptv.R;
import com.app.newiptv.base.BaseActivity;
import com.app.newiptv.base.MyApplication;
import com.app.newiptv.bean.ProgramBean;
import com.app.newiptv.bean.SitcomInfos;
import com.app.newiptv.bean.allchannels.MainChanel;
import com.app.newiptv.bean.allchannels.Program;
import com.app.newiptv.helper.MySQLiteOpenHelper;
import com.app.newiptv.helper.MySitcomIndexOpenHelper;
import com.app.newiptv.presenter.PlayerPresneter;
import com.app.newiptv.utils.APPLog;
import com.app.newiptv.utils.CacheDataPresenter;
import com.app.newiptv.utils.SystemTimeDate;
import com.app.newiptv.view.LoadingView;
import com.app.newiptv.view.ScrollTextView;
import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videocontroller.component.CompleteView;
import com.dueeeke.videocontroller.component.VodControlView;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.util.L;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.app.newiptv.activity.Contast.TAG;

public class PlayerActivity extends BaseActivity<VideoView> {
    private String playUrl = "";
    private int TIME_OVER = 1;
    private int BROW_TEIM = 3;
    private int UPDATA_NUMBER = 8;
    private int TO_PLAYER = 9;
    private int HIDE_WINDOW = 10;
    private int LIVE_CHANNEL = 11;
    private int PROGRAM_CHANNEL = 12;
    private FrameLayout singleView;
    private ImageView pasusImage;
    private SeekBar progressBar;
    private TextView currentText;
    private TextView alText;
    private ProgramBean.DataBean detailsBean;
    private List<SitcomInfos> indexPrograms = new ArrayList<>();
    private PlayerPresneter mPlayerPresneter;
    private long count;
    private long allCount;
    private String currentTime;
    private String allTime;
    private TextView program_name;
    private TextView actor_text;
    private TextView info_text;
    private ScrollTextView test_happy_view;
    private int SET_ADD_DURATION = 0x04;
    private int SET_REDUCE_DURATION = 0x05;
    private int SET_SEEK_TO = 0x06;
    private RelativeLayout bar_layout;
    private int type;
    private static final int VOD_TYPE = 1001; ///电影
    private static final int TELE_TYPE = 1000; //电视剧
    private static final int LIVE_TYPE = 1002;//直播
    private static final int TVOD_TYPE = 1003;//回看
    private static final int SKIP_TYPE = 1004;//默认播放频道
    private static final int COLLECTION = 1006;//收藏
    private static final int CHANNEL = 1007;
    private int CANCLE_TYPE = 1005;//下一集
    private int NEXT_TYPE = 1004;//下一集
    private RelativeLayout play_type;
    private RelativeLayout play_actor_type;
    private TextView live_number;
    private Program mProgram;
    private RelativeLayout activity_player;
    private List<String> sourcesList;
    private int number = -1;
    private int indexId;
    private int index;
    private int Current_Type;//当前播放状态
    private String numberText = "";
    //直播
    private TextView live_name;
    private TextView live_current_text;
    private TextView time_current_text;
    private TextView live_play_later;
    private TextView time_play_later;
    private int currentPosition;
    private SharedPreferences sharePreferences;
    private int programId;
    private RelativeLayout pause_layout;
    private Intent intent;
    private FrameLayout channelListLayout;
    private PlayWindowFragment playWindowFragment;
    private int CHANGE_CHANNEL = 1008;
    private static final int DESTORY_MEDIA = 1009;
    private View seekLayout;
    public List<MainChanel> listContent;
    private VodControlView vodControlView;
    private List<MainChanel.Lives> liveList = new ArrayList<>();
    private Boolean addTag = false;
    private Boolean reduceTag = false;
    private List<MainChanel.Lives>  sortList=new ArrayList<>();

    private Map<String, MainChanel.Lives> livesMap = new HashMap<>();

    private Map<String, MainChanel.Lives> idMap = new HashMap<>();
    private LoadingView progress;
    private SQLiteDatabase writeDatabase;
    private SQLiteDatabase readDatabase;
    private SQLiteDatabase writeInstance;
    private SQLiteDatabase readInstance;
    private Integer play_time;
    private String[] sitcomIndexs;
    private String movieName;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_player;
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            listContent = CacheDataPresenter.getPresenter(PlayerActivity.this).getListContent();
            if (null == listContent) {
                listContent = new ArrayList<>();
            }
            int i = 0;
            for (MainChanel chanel : listContent) {
                for (MainChanel.Lives lives : chanel.getLives()) {
                    i++;
                    lives.setSort(i);
                    liveList.add(lives);
                    sortList.add(lives);
                    livesMap.put(lives.getNumber() + "", lives);
                }
            }
            Collections.sort(sortList, new Comparator<MainChanel.Lives>() {
                @Override
                public int compare(MainChanel.Lives lives, MainChanel.Lives t1) {
                    return lives.getNumber()>t1.getNumber()?1:-1;
                }
            });

            choosePlayType();
        }
    };

    public int getIndexId() {
        if (liveList.isEmpty()) {
            return 0;
        }
        return liveList.get(index).getId();
    }

    public int getIndex() {
        return index;
    }

    private void choosePlayType() {
        switch (type) {
            case VOD_TYPE:
                //电影
                Current_Type = VOD_TYPE;
                play_type.setVisibility(View.VISIBLE);
                play_actor_type.setVisibility(View.GONE);
                detailsBean = (ProgramBean.DataBean) intent.getSerializableExtra("data");
                int position1 = intent.getIntExtra("position", 0);
                String currentUrl = detailsBean.getList().get(position1).getVod_play_url();
                if (currentUrl.contains("$")) {
                    playUrl = currentUrl.split("\\$")[1];
                }
                APPLog.printInfo("playerUrl==>:" + playUrl);
                break;
            case TELE_TYPE:
                //电影
                Current_Type = TELE_TYPE;
                play_type.setVisibility(View.VISIBLE);
                play_actor_type.setVisibility(View.GONE);
                detailsBean = (ProgramBean.DataBean) intent.getSerializableExtra("data");
                int position2 = intent.getIntExtra("position", 0);
                currentPosition = position2;
                String urls = detailsBean.getList().get(0).getVod_play_url();
                String[] sitcoms = urls.split("#");
                for (int i=0;i<sitcoms.length;i++) {
                    if (!sitcoms[i].startsWith("?token=")) {
                        String[] sitcom = sitcoms[i].split("\\$");
                        indexPrograms.add(new SitcomInfos(sitcom[0], sitcom[1]));
                    }
                }
                if (position2 >= indexPrograms.size()) {
                    return;
                }
                playUrl = indexPrograms.get(position2).getUrl();
                APPLog.printInfo("playerUrl==>:" + playUrl);
                break;
            case LIVE_TYPE:
                //直播
                Current_Type = LIVE_TYPE;
                play_type.setVisibility(View.GONE);
                play_actor_type.setVisibility(View.VISIBLE);
                mProgram = (Program) intent.getSerializableExtra("data");
                indexId = mProgram.getId();


                for (int i = 0; i < liveList.size(); i++) {
                    MainChanel.Lives lives = liveList.get(i);
                    if (indexId == lives.getId()) {
                        index = i;
                        programId = indexId;
                        writeChannelId(indexId);
                        number = lives.getNumber();
                        sourcesList = lives.getSources();
                        playUrl = sourcesList.get(0);
                        live_number.setText(lives.getNumber() + "");
                        live_number.setVisibility(View.VISIBLE);
                        mHandler.sendEmptyMessageDelayed(UPDATA_NUMBER, 3000);
                    }
                }
                break;
            case TVOD_TYPE:
                Current_Type = VOD_TYPE;
                play_type.setVisibility(View.VISIBLE);
                play_actor_type.setVisibility(View.GONE);
                playUrl = intent.getStringExtra("playUrl");
                break;
            case SKIP_TYPE:
                Current_Type = LIVE_TYPE;
                type = LIVE_TYPE;
                play_type.setVisibility(View.GONE);
                play_actor_type.setVisibility(View.VISIBLE);
                indexId = intent.getIntExtra("index", 0);


                for (int i = 0; i < liveList.size(); i++) {
                    MainChanel.Lives lives = liveList.get(i);
                    if (indexId == lives.getId()) {
                        index = i;
                        programId = indexId;

                        number = lives.getNumber();
                        sourcesList = lives.getSources();

                        if (!sourcesList.isEmpty()) {
                            playUrl = sourcesList.get(0);
                            live_number.setText(lives.getNumber() + "");
                            live_number.setVisibility(View.VISIBLE);
                            mHandler.sendEmptyMessageDelayed(UPDATA_NUMBER, 3000);
                        }

                    }
                }
                break;
        }
    }

    protected void initView() {
        super.initView();
        progress = new LoadingView(this);
        seekLayout=findViewById(R.id.seek_layout);
        singleView = (FrameLayout) this.findViewById(R.id.single_bar);
        pasusImage = (ImageView) this.findViewById(R.id.pause_image);
        progressBar = (SeekBar) this.findViewById(R.id.seek_bar);
        alText = (TextView) this.findViewById(R.id.all_tiem);
        currentText = (TextView) this.findViewById(R.id.current_tiem);
        bar_layout = (RelativeLayout) this.findViewById(R.id.bar_layout);
        sharePreferences = getSharedPreferences("channel", 0);
        program_name = (TextView) findViewById(R.id.program_name);
        actor_text = (TextView) findViewById(R.id.actor_text);
        info_text = (TextView) findViewById(R.id.info_text);
        pause_layout = (RelativeLayout) findViewById(R.id.pause_layout);
        test_happy_view = (ScrollTextView) findViewById(R.id.s_tv);
        test_happy_view.startScroll();
        play_type = (RelativeLayout) findViewById(R.id.play_type);
        play_actor_type = (RelativeLayout) findViewById(R.id.play_actor_type);
        live_number = (TextView) findViewById(R.id.live_number);
        live_number.setTypeface(MyApplication.face);
        activity_player = (RelativeLayout) findViewById(R.id.activity_player);

        //直播
        live_name = (TextView) findViewById(R.id.live_name);
        live_current_text = (TextView) findViewById(R.id.live_current_text);
        time_current_text = (TextView) findViewById(R.id.time_current_text);
        live_play_later = (TextView) findViewById(R.id.live_play_later);
        time_play_later = (TextView) findViewById(R.id.time_play_later);
        channelListLayout = (FrameLayout) this.findViewById(R.id.channel_list);
        bar_layout.setOnKeyListener(new OnKeyListen());
        MySQLiteOpenHelper sqlHelper = MySQLiteOpenHelper.getInstance(this);
        MySitcomIndexOpenHelper sitcommHelper = MySitcomIndexOpenHelper.getInstance(this);
        writeDatabase = sqlHelper.getWriteInstance();
        readDatabase = sqlHelper.getReadInstance();
        readInstance = sitcommHelper.getReadInstance();
        writeInstance = sitcommHelper.getWriteInstance();
        intent = getIntent();
        type = intent.getIntExtra("type", 0);
        play_time = intent.getIntExtra("play_time", 0);
        Integer sitcom_index = intent.getIntExtra("sitcom_index", 0);
        listContent = CacheDataPresenter.getPresenter(this).getListContent();
        if (null == listContent) {
            listContent = new ArrayList<>();
        }
        int i = 0;
        for (MainChanel chanel : listContent) {
            for (MainChanel.Lives lives : chanel.getLives()) {
                if(null==idMap.get(lives.getId()+""))
                {
                    idMap.put(lives.getId()+"",lives);
                    i++;
                    lives.setSort(i);
                    liveList.add(lives);
                    sortList.add(lives);
                    livesMap.put(lives.getNumber() + "", lives);
                }
            }
        }

        Collections.sort(sortList, new Comparator<MainChanel.Lives>() {
            @Override
            public int compare(MainChanel.Lives lives, MainChanel.Lives t1) {
                return lives.getNumber()>t1.getNumber()?1:-1;
            }
        });

        choosePlayType();
        initData();
        if (type == 1000 && sitcom_index !=0) {
            playUrl = indexPrograms.get(sitcom_index).getUrl();
        }
        crearPlayer(playUrl);
    }

    private VideoView.OnStateChangeListener mOnStateChangeListener = new VideoView.SimpleOnStateChangeListener() {
        @Override
        public void onPlayerStateChanged(int playerState) {
            switch (playerState) {
                case VideoView.PLAYER_NORMAL://小屏
                    break;
                case VideoView.PLAYER_FULL_SCREEN://全屏
                    break;
            }
        }

        @Override
        public void onPlayStateChanged(int playState) {
            switch (playState) {
                case VideoView.STATE_IDLE:
                    break;
                case VideoView.STATE_PREPARING:
                    progress.show();
                    //在STATE_PREPARING时设置setMute(true)可实现静音播放
//                    mVideoView.setMute(true);
                    break;
                case VideoView.STATE_PREPARED:
                    Log.i(TAG, "onPrepared: ");
                    progress.dismiss();
                    if (play_time != 0) {
                        mVideoView.seekTo(play_time);
                    }
                    if (mHandler.hasMessages(DESTORY_MEDIA)) {
                        mHandler.removeMessages(DESTORY_MEDIA);
                    }
                    if (mVideoView != null) {
                        try {
                            mVideoView.start();
                            if (Current_Type != 1002) {
                                allCount = mVideoView.getDuration();
                                progressBar.setMax(new Long(allCount).intValue());
                                allTime = SystemTimeDate.formatTime(new Long(allCount).intValue());
                                currentTime = SystemTimeDate.formatTime(0);
                                currentText.setText(currentTime);
                                alText.setText(allTime);
                                mHandler.sendEmptyMessage(BROW_TEIM);
                                if(Current_Type==1003)
                                {
                                    seekLayout.setVisibility(View.VISIBLE);
                                    bar_layout.requestFocus();
                                }
                                APPLog.printInfo("allCount:" + allCount);
                            }
                        } catch (Exception e) {
                            APPLog.printInfo("e:" + e);
                        }
                    }
                    break;
                case VideoView.STATE_PLAYING:
                    //需在此时获取视频宽高
                    int[] videoSize = mVideoView.getVideoSize();
                    L.d("视频宽：" + videoSize[0]);
                    L.d("视频高：" + videoSize[1]);
                    break;
                case VideoView.STATE_PAUSED:
                    vodControlView.mBottomContainer.setVisibility(View.VISIBLE);
                    break;
                case VideoView.STATE_BUFFERING:
                    break;
                case VideoView.STATE_BUFFERED:
                    break;
                case VideoView.STATE_PLAYBACK_COMPLETED:
                    if (type == TELE_TYPE) {
                        //电视剧 自动播放下一级
                        if (indexPrograms.size() == 0) {
                            detailsBean.getList().get(0).getVod_play_url();
                            String urls = detailsBean.getList().get(0).getVod_play_url();
                            String[] sitcoms = urls.split("#");
                            for (int i=0;i<sitcoms.length;i++){
                                if (!sitcoms[i].startsWith("?token=")) {
                                    String[] sitcom = sitcoms[i].split("\\$");
                                    indexPrograms.add(new SitcomInfos(sitcom[0], sitcom[1]));
                                }
                            }
                        }
                        if (null != indexPrograms && indexPrograms.size() > 0) {
                            if (currentPosition < indexPrograms.size() - 1) {
                                currentPosition++;
                                playUrl = indexPrograms.get(currentPosition).getUrl();
                                crearPlayer(playUrl);
                                Toast.makeText(PlayerActivity.this, "播放第" + (currentPosition+1) + "集", Toast.LENGTH_SHORT).show();
                                Log.i("knight", "onCompletion: " + currentPosition);
                                return;
                            } else {
                                finish();
                                return;
                            }
                        } else {
                            finish();
                        }
                    } else {
                        finish();
                    }
                    break;
                case VideoView.STATE_ERROR:
                    progress.dismiss();
                    break;
            }
        }
    };

    private void initData() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("PlayerActivity");
        registerReceiver(receiver, filter);
        live_name.setTypeface(MyApplication.face);
        live_current_text.setTypeface(MyApplication.face);
        time_current_text.setTypeface(MyApplication.face);
        live_play_later.setTypeface(MyApplication.face);
        time_play_later.setTypeface(MyApplication.face);
        alText.setTypeface(MyApplication.face);
        currentText.setTypeface(MyApplication.face);
        program_name.setTypeface(MyApplication.face);
        actor_text.setTypeface(MyApplication.face);
        info_text.setTypeface(MyApplication.face);
        mPlayerPresneter = new PlayerPresneter(this);

        if (type == LIVE_TYPE) {
            seekLayout.setVisibility(View.INVISIBLE);
        }else if(type==VOD_TYPE||type==TELE_TYPE)
        {
            singleView.setVisibility(View.VISIBLE);
            //seekLayout.setVisibility(View.VISIBLE);
        }
        switch (type) {
            case VOD_TYPE:
            case TELE_TYPE:
                //电视剧/电影
                if (detailsBean != null) {
                    movieName = detailsBean.getList().get(0).getVod_name();
                    program_name.setText(movieName);
                    Cursor sitcomCursor = readInstance.query("SitcomIndex", null, "name="+ "'" +movieName + "'", null, null, null, null);
                    if (sitcomCursor.moveToFirst()) {
                        String sitcom_index = sitcomCursor.getString(sitcomCursor.getColumnIndex("sitcom_index"));
                        sitcomIndexs = sitcom_index.split(",");
                    }
                    //导演：王晶，孙总   演员：徐总|孙总|百望山
                    actor_text.setText("导演：" + detailsBean.getList().get(0).getVod_director() + "      演员：" + detailsBean.getList().get(0).getVod_actor());
                    info_text.setText(detailsBean.getList().get(0).getVod_content());
                }
                bar_layout.requestFocus();

                break;
            case LIVE_TYPE:
                //直播
                mPlayerPresneter.setCallback(callback);
                mPlayerPresneter.setDisplayed(true);
                mPlayerPresneter.loadVodItem(indexId);
                break;
        }

        pasusImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVideoView.isPlaying()) {
                    mVideoView.pause();
                } else {
                    mVideoView.start();
                }
            }
        });
        if (Contast.CHANNEL_MARQUEE != null) {
            test_happy_view.setVisibility(View.VISIBLE);
            test_happy_view.setText(Contast.CHANNEL_MARQUEE);
        }
    }
    public void updataTime() {
        mHandler.sendEmptyMessageDelayed(BROW_TEIM, 1000);
    }



    public void crearPlayer(String url) {
        Log.i(TAG, "crearPlayer: " + url);
        if (mVideoView != null) {
            mVideoView.release();
        }
        mVideoView = findViewById(R.id.player);
        StandardVideoController controller = new StandardVideoController(this);
        //根据屏幕方向自动进入/退出全屏
        controller.addControlComponent(new CompleteView(this));//自动完成播放界面
        vodControlView = new VodControlView(this);//点播控制条
        controller.addControlComponent(vodControlView);
        mVideoView.setVideoController(controller);
        mVideoView.addOnStateChangeListener(mOnStateChangeListener);
        mVideoView.setUrl(url);
        mVideoView.start();
        if (Current_Type != TVOD_TYPE) {
            singleView.setVisibility(View.VISIBLE);
            mHandler.sendEmptyMessageDelayed(1, 6000);
        }
    }

    @Override
    protected void onStop() {
        if (mVideoView != null) {
            mVideoView.release();
            mVideoView = null;
        }
        super.onStop();
    }

    //快进循环发送消息
    public void setAddDuration() {
        mHandler.sendEmptyMessageDelayed(SET_ADD_DURATION, 1000);
    }

    //快退循环发送
    public void setReduceDuration() {
        mHandler.sendEmptyMessageDelayed(SET_REDUCE_DURATION, 1000);
    }


    public class OnKeyListen implements View.OnKeyListener {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            Log.d("tag", "--------OnKeyEvent--------" + keyCode);
            if ((keyCode == 22 || keyCode == 90) && event.getAction() == KeyEvent.ACTION_DOWN) {
                if (singleView.getVisibility() == View.INVISIBLE) {
                    singleView.setVisibility(View.VISIBLE);
                }
                if (mHandler.hasMessages(BROW_TEIM)) {
                    mHandler.removeMessages(BROW_TEIM);
                }
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                if (mHandler.hasMessages(SET_SEEK_TO)) {
                    mHandler.removeMessages(SET_SEEK_TO);
                }
                setAddDuration();
                return true;
            } else if ((keyCode == 22 || keyCode == 90) && event.getAction() == KeyEvent.ACTION_UP) {
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                if (mHandler.hasMessages(SET_ADD_DURATION)) {
                    mHandler.removeMessages(SET_ADD_DURATION);
                }
                mHandler.sendEmptyMessageDelayed(BROW_TEIM, 1000);
                mHandler.sendEmptyMessageDelayed(TIME_OVER, 6000);
                mHandler.sendEmptyMessage(SET_SEEK_TO);
                APPLog.printInfo("快进====");
                return true;
            } else if ((keyCode == 21 || keyCode == 89) && event.getAction() == KeyEvent.ACTION_DOWN) {
                if (mHandler.hasMessages(BROW_TEIM)) {
                    mHandler.removeMessages(BROW_TEIM);
                }
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                if (mHandler.hasMessages(SET_SEEK_TO)) {
                    mHandler.removeMessages(SET_SEEK_TO);
                }
                setReduceDuration();
                return true;
            } else if ((keyCode == 21 || keyCode == 89) && event.getAction() == KeyEvent.ACTION_UP) {
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                if (mHandler.hasMessages(SET_REDUCE_DURATION)) {
                    mHandler.removeMessages(SET_REDUCE_DURATION);
                }
                mHandler.sendEmptyMessageDelayed(TIME_OVER, 6000);
                mHandler.sendEmptyMessageDelayed(BROW_TEIM, 1000);
                mHandler.sendEmptyMessage(SET_SEEK_TO);
                return true;
            } else if ((keyCode == 23 || keyCode == 86) && event.getAction() == KeyEvent.ACTION_DOWN) {
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                mHandler.sendEmptyMessageDelayed(TIME_OVER, 6000);
                if (mVideoView != null) {
                    if (mVideoView.isPlaying()) {
                        mVideoView.pause();
                        pause_layout.setVisibility(View.VISIBLE);
                    } else {
                        mVideoView.start();
                        pause_layout.setVisibility(View.GONE);
                    }
                }
                return true;
            }
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == CANCLE_TYPE && requestCode == VOD_TYPE) {
            if (mVideoView != null) {
                ProgramBean.DataBean.ListBean listBean = detailsBean.getList().get(0);
                Cursor cursor = readDatabase.query("RecodeCollect", null, "name=" + "'" + listBean.getVod_name() + "'"+" and " + "type=0", null, null, null, null);
                boolean exist = cursor.moveToFirst();
                cursor.close();
                if (exist) {
                    ContentValues values = new ContentValues();
                    values.put("collect_time", System.currentTimeMillis());
                    values.put("play_time", mVideoView.getCurrentPosition());
                    writeDatabase.update("RecodeCollect", values, "name=" + "'" + listBean.getVod_name() + "'"+" and " + "type=0", null);
                } else {
                    ContentValues values = new ContentValues();
                    values.put("pic_url", listBean.getVod_pic());
                    values.put("name", listBean.getVod_name());
                    values.put("actor", listBean.getVod_actor());
                    values.put("type", 0);
                    values.put("collect_time", System.currentTimeMillis());
                    values.put("movie_id", listBean.getVod_id());
                    values.put("movie_type", type);
                    values.put("play_time", mVideoView.getCurrentPosition());
                    Log.i("legendki", "onClick: " + values);
                    writeDatabase.insert("RecodeCollect",null,values);
                }
                mVideoView.release();
                mVideoView = null;
            }
            finish();
        } else if (resultCode == CANCLE_TYPE && requestCode == TELE_TYPE) {
            ProgramBean.DataBean.ListBean listBean = detailsBean.getList().get(0);
            Cursor cursor = readDatabase.query("RecodeCollect", null, "name=" + "'" + listBean.getVod_name() + "'"+" and " + "type=0", null, null, null, null);
            boolean exist = cursor.moveToFirst();
            cursor.close();
            if (exist) {
                ContentValues values = new ContentValues();
                values.put("collect_time", System.currentTimeMillis());
                values.put("play_time", mVideoView.getCurrentPosition());
                values.put("sitcom_index", currentPosition);
                writeDatabase.update("RecodeCollect", values, "name=" + "'" + listBean.getVod_name() + "'"+" and " + "type=0", null);
            } else {
                ContentValues values = new ContentValues();
                values.put("pic_url", listBean.getVod_pic());
                values.put("name", listBean.getVod_name());
                values.put("actor", listBean.getVod_actor());
                values.put("type", 0);
                values.put("collect_time", System.currentTimeMillis());
                values.put("movie_id", listBean.getVod_id());
                values.put("movie_type", type);
                values.put("play_time", mVideoView.getCurrentPosition());
                values.put("sitcom_index", currentPosition);
                Log.i("legendki", "onClick: " + values);
                writeDatabase.insert("RecodeCollect",null,values);
            }
            if (mVideoView != null) {
                mVideoView.release();
                mVideoView = null;
            }
            finish();
        } else if (resultCode == NEXT_TYPE && requestCode == TELE_TYPE) {
            int saveIndex = intent.getIntExtra("sitcom_index", 0);
            if (saveIndex != 0) {
                currentPosition = saveIndex;
            }
            play_time = 0;
            currentPosition++;
            String indexName = indexPrograms.get(currentPosition).getName();
            Cursor sitcomCursor = readInstance.query("SitcomIndex", null, "name="+ "'" +movieName + "'", null, null, null, null);
            if (sitcomCursor.moveToFirst()) {
                String sitcom_index = sitcomCursor.getString(sitcomCursor.getColumnIndex("sitcom_index"));
                sitcomIndexs = sitcom_index.split(",");
            }

            if (sitcomIndexs!= null && !Arrays.asList(sitcomIndexs).contains(indexName)) {
                String sitcom_index = "";
                for (int i = 0; i < sitcomIndexs.length; i++) {
                    sitcom_index = sitcom_index + sitcomIndexs[i] + ",";
                }
                sitcom_index = sitcom_index + indexName + ",";
                ContentValues values = new ContentValues();
                values.put("name", movieName);
                values.put("sitcom_index", sitcom_index);
                writeInstance.update("SitcomIndex", values, "name=" + "'" + movieName + "'", null);
            }
            if (indexPrograms.size() > currentPosition) {
                String movieName = program_name.getText().toString().trim();
                playUrl = indexPrograms.get(currentPosition).getUrl();
                crearPlayer(playUrl);
                pause_layout.setVisibility(View.GONE);
            } else {
                Toast.makeText(this, "已经是最后一集了", Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == CANCLE_TYPE && requestCode == LIVE_TYPE) {
            if (mVideoView != null) {
                mVideoView.release();
                mVideoView = null;
            }
            finish();
        } else if (resultCode == LIVE_TYPE && requestCode == LIVE_TYPE) {

        } else if (resultCode == CANCLE_TYPE && requestCode == TVOD_TYPE) {
            if (mVideoView != null) {
//                mVideoView.stop();
                mVideoView.release();
                mVideoView = null;
                ProgramBean.DataBean.ListBean listBean = detailsBean.getList().get(0);
            }
            finish();
        } else if (requestCode == TVOD_TYPE && requestCode == TVOD_TYPE) {

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("tag", "--------KeyEvent--------" + keyCode+" Current_Type:"+Current_Type+" vi:"+singleView.getVisibility());
        if ((keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) && event.getAction() == KeyEvent.ACTION_DOWN) {
            //直播屏蔽左右键
            if (Current_Type == LIVE_TYPE) {
                return true;
            }
            if (singleView.getVisibility() != View.VISIBLE) {
                singleView.setVisibility(View.VISIBLE);
                seekLayout.setVisibility(View.VISIBLE);
                mHandler.sendEmptyMessage(BROW_TEIM);
                bar_layout.requestFocus();
            }
            if(!bar_layout.hasFocus())
            {
                mHandler.removeMessages(BROW_TEIM);
                mHandler.sendEmptyMessage(BROW_TEIM);
                bar_layout.requestFocus();
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                Intent intent = new Intent(this, ExitActivity.class);
                switch (type) {
                    case VOD_TYPE:
                        intent.putExtra("playType", VOD_TYPE);
                        startActivityForResult(intent, VOD_TYPE);
                        break;
                    case TELE_TYPE:
                        intent.putExtra("playType", TELE_TYPE);
                        startActivityForResult(intent, TELE_TYPE);
                        break;
                    case LIVE_TYPE:
                        intent.putExtra("playType", LIVE_TYPE);
                        startActivityForResult(intent, TELE_TYPE);
                        break;
                    case TVOD_TYPE:
                        intent.putExtra("playType", TVOD_TYPE);
                        startActivityForResult(intent, TVOD_TYPE);
                        break;
                }
            }
            return true;
        } else if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9 && event.getAction() == KeyEvent.ACTION_DOWN) {
            setNumber(keyCode);
            return true;
        } else if ((keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mHandler.hasMessages(0x11)) {
                return true;
            }
            mHandler.sendEmptyMessageDelayed(0x11, 1000);
            if (Current_Type == LIVE_TYPE || Current_Type == TVOD_TYPE) {
                if (playWindowFragment == null) {
                    playWindowFragment = new PlayWindowFragment();
                    playWindowFragment.setContext(this);
                    playWindowFragment.setMainHandler(mHandler);
                    playWindowFragment.setFragmentManager(getFragmentManager());
                }
                getFragmentManager().beginTransaction().add(R.id.channel_list, playWindowFragment).commit();
                APPLog.printInfo("开始显示频道列表");
            } else {
                if (mHandler.hasMessages(TIME_OVER)) {
                    mHandler.removeMessages(TIME_OVER);
                }
                mHandler.sendEmptyMessageDelayed(TIME_OVER, 6000);
                if (mVideoView != null) {
                    if (mVideoView.isPlaying()) {
                        mVideoView.pause();
                        pause_layout.setVisibility(View.VISIBLE);
                    } else {
                        mVideoView.start();
                        pause_layout.setVisibility(View.GONE);
                    }
                }
            }
            return true;
        } else if ((keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_CHANNEL_DOWN) && event.getAction() == KeyEvent.ACTION_DOWN) {

            Log.d("Player",event.getAction() +" Current_Type "+Current_Type+" index:"+index+" liveList.size():"+liveList.size());

            if (Current_Type == LIVE_TYPE) {
                if (index >= 0) {
                    if (liveList != null && index >= 0 && index < liveList.size()) {
                        if (mHandler.hasMessages(UPDATA_NUMBER)) {
                            mHandler.removeMessages(UPDATA_NUMBER);
                        }
                        if (mHandler.hasMessages(CHANGE_CHANNEL)) {
                            mHandler.removeMessages(CHANGE_CHANNEL);
                        }

                        //获取当前的
                        MainChanel.Lives tmpBean = liveList.get(index);

                        int sortIndex=sortList.indexOf(tmpBean);
                        sortIndex--;
                        if(sortIndex<0)
                        {
                            sortIndex=liveList.size()-1;
                        }

                        MainChanel.Lives  listBean=sortList.get(sortIndex);
                        index=liveList.indexOf(listBean);
                        Log.d("tag", "----DOWN--->" + listBean.getName());
                        sourcesList = listBean.getSources();
                        live_number.setText(listBean.getNumber() + "");
                        live_number.setVisibility(View.VISIBLE);

                        Log.d("Player",event.getAction() +" Current_Type "+Current_Type+" index:"+index+" liveList.size():"+listBean.getName());

                        mHandler.removeCallbacksAndMessages(null);
                        mHandler.sendEmptyMessageDelayed(UPDATA_NUMBER, 3000);
                        mHandler.sendEmptyMessageDelayed(CHANGE_CHANNEL, 500);
                    }
                }
            }
            return true;
        } else if ((keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_CHANNEL_UP) && event.getAction() == KeyEvent.ACTION_DOWN) {
            Log.d("Player",event.getAction() +" Current_Type "+Current_Type+" index:"+index+" liveList.size():"+liveList.size());

            if (Current_Type == LIVE_TYPE) {
                if (index < liveList.size()) {
                    if (liveList != null && index >= 0 && index < liveList.size()) {
                        if (mHandler.hasMessages(UPDATA_NUMBER)) {
                            mHandler.removeMessages(UPDATA_NUMBER);
                        }
                        if (mHandler.hasMessages(CHANGE_CHANNEL)) {
                            mHandler.removeMessages(CHANGE_CHANNEL);
                        }
                        //获取当前的
                        MainChanel.Lives tmpBean = liveList.get(index);
                        int sortIndex=sortList.indexOf(tmpBean);
                        sortIndex++;
                        if(sortIndex>=liveList.size())
                        {
                            sortIndex=0;
                        }
                        MainChanel.Lives  listBean=sortList.get(sortIndex);
                        index=liveList.indexOf(listBean);
                        Log.d("tag", "----DOWN--->" + listBean.getName());
                        sourcesList = listBean.getSources();
                        number=listBean.getNumber();
                        live_number.setText(listBean.getNumber() + "");
                        live_number.setVisibility(View.VISIBLE);
                        Log.d("Player",event.getAction() +" Current_Type "+Current_Type+" index:"+index+" liveList.size():"+listBean.getName());
                        mHandler.removeCallbacksAndMessages(null);
                        mHandler.sendEmptyMessageDelayed(UPDATA_NUMBER, 3000);
                        mHandler.sendEmptyMessageDelayed(CHANGE_CHANNEL, 500);
                    }
                }
            }
            return true;
        }
        return false;
    }

    private PlayerPresneter.Callback callback = new PlayerPresneter.Callback() {
        @Override
        public void onError(int code, String msg) {
            APPLog.printDebug("callback code "+code+" msg:"+msg);

        }

        @Override
        public void onPlayerUrlCompleted(PlayerPresneter presenter, int count) {
            APPLog.printDebug("callback code "+count);
            if (presenter != null) {
                presenter.onBindMovieView(itemViewHolder, count);
                play_actor_type.setVisibility(View.VISIBLE);
                mHandler.sendEmptyMessageDelayed(TIME_OVER, 6 * 1000);
            }
        }
    };
    private PlayerPresneter.ItemViewHolder itemViewHolder = new PlayerPresneter.ItemViewHolder() {
        @Override
        public void setChannelName(String name) {
            live_name.setText(name);
        }

        @Override
        public void setCurrentPlay(String text) {
            Log.d("setLaterPlay", "live_current_text :"+text);
            live_current_text.setText(text.trim());
        }

        @Override
        public void setCurrentPlayTime(String text) {
            Log.d("setLaterPlay", "time_current_text :"+text);
            time_current_text.setText(text.trim());
        }

        @Override
        public void setLaterPlay(String text) {
            Log.d("setLaterPlay", "live_play_later :"+text);
            live_play_later.setText(text.trim());
        }

        @Override
        public void setLaterPlaytime(String text) {
            Log.d("setLaterPlay", "time_play_later :"+text);
            time_play_later.setText(text.trim());
        }
    };

    private void setNumber(int number) {

        if(Current_Type!=LIVE_TYPE)
        {
            return;
        }
        number -= 7;
        APPLog.printDebug(numberText+" number: "+number);
        mHandler.removeMessages(TO_PLAYER);
        if ( numberText.length() < 2) {
            numberText = numberText + number;
            live_number.setText(numberText);
            live_number.setVisibility(View.VISIBLE);
            mHandler.sendEmptyMessageDelayed(TO_PLAYER, 2000);
        } else if (numberText.length() >= 2) {
            numberText = numberText + number;
            numberText=numberText.substring(numberText.length()-3);
            APPLog.printDebug(numberText+" number: "+number);
            live_number.setText(numberText);
            live_number.setVisibility(View.VISIBLE);
            Message message = new Message();
            message.what = TO_PLAYER;
            mHandler.sendMessageDelayed(message, 1000);
        }

        APPLog.printDebug(numberText+" number: "+number);
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == TIME_OVER) {
                singleView.setVisibility(View.INVISIBLE);
            } else if (msg.what == BROW_TEIM) {
                try {
                    count = mVideoView.getCurrentPosition();
                    String curTime = SystemTimeDate.formatTime(new Long(count).intValue());
                    long allTime = mVideoView.getDuration();
                    currentText.setText(curTime);
                    vodControlView.mBottomProgress.setProgress(new Long(count).intValue());
                    vodControlView.mVideoProgress.setProgress(new Long(count).intValue());
                    if (count >= allTime - 3000) {
//                        onCompletion(mVideoView);
                        return;
                    }
                } catch (Exception e) {
                    APPLog.printInfo("获取长度异常：" + e);
                }
            } else if (msg.what == SET_ADD_DURATION) {
                if (progressBar != null) {
                    if (count != allCount - 10000) {
                        count += 10 * 1000;
                    }
                    if (count >= allCount) {
                        count = allCount - 10000;
                    }
                    if (count == allCount - 10000) {
                        return;
                    }
                    APPLog.printInfo("addcount:" + count);
                    progressBar.setProgress(new Long(count).intValue());
                    String currentTime = SystemTimeDate.formatTime(new Long(count).intValue());
                    currentText.setText(currentTime);
                }
            } else if (msg.what == SET_REDUCE_DURATION) {
                if (progressBar != null) {
                    count -= 10 * 1000;
                    if (count <= 0) {
                        count = 0;
                    }
                    if (count == 0) {
                        return;
                    }
                    progressBar.setProgress(new Long(count).intValue());
                    String currentTime = SystemTimeDate.formatTime(new Long(count).intValue());
                    currentText.setText(currentTime);
                }
            } else if (msg.what == SET_SEEK_TO) {
                if (mVideoView != null) {
                    mVideoView.seekTo(new Long(count).intValue());
                }
                mHandler.removeMessages(BROW_TEIM);
                try {
                    Thread.sleep(2000);
//                    vodControlView.mBottomContainer.setVisibility(View.INVISIBLE);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else if (msg.what == UPDATA_NUMBER) {
                live_number.setVisibility(View.GONE);
            } else if (msg.what == TO_PLAYER) {
                boolean isexist = false;
                MainChanel.Lives liveListBean = livesMap.get(numberText);
                if (null != liveListBean) {
                    playLive(liveListBean);
                    isexist=true;
                }
                live_number.setVisibility(View.GONE);
                numberText = "";
                if (!isexist) {
                    Toast.makeText(PlayerActivity.this, "暂无节目", Toast.LENGTH_SHORT).show();
                }
            } else if (msg.what == HIDE_WINDOW) {

            } else if (msg.what == CHANNEL) {
                try {
                    if (!"".endsWith(playUrl)) {
                        crearPlayer(playUrl);
                    }
                } catch (Exception e) {
                    APPLog.printInfo("播放失败");
                }
            } else if (msg.what == LIVE_CHANNEL) {
                Program program = (Program) msg.obj;
                if (program != null) {
                    playUrl = program.getSources().get(0);
                    Log.d("tag", "----playUrl----" + playUrl);
                    crearPlayer(playUrl);
                    mProgram = program;
                    writeChannelId(program.getId());
                    mPlayerPresneter.setCallback(callback);
                    mPlayerPresneter.setDisplayed(true);
                    mPlayerPresneter.loadVodItem(program.getId());

                    indexId = mProgram.getId();

                    for (int i = 0; i < liveList.size(); i++) {
                        MainChanel.Lives liveListBean = liveList.get(i);
                        if (indexId == liveListBean.getId()) {
                            index = i;
                            programId = indexId;
                            number = liveListBean.getNumber();
                            live_number.setText(liveListBean.getNumber() + "");
                            live_number.setVisibility(View.VISIBLE);
                            mHandler.sendEmptyMessageDelayed(UPDATA_NUMBER, 3000);
                            break;
                        }
                    }
                }
            } else if (msg.what == PROGRAM_CHANNEL) {
                Bundle bundle = (Bundle) msg.obj;
                Current_Type = bundle.getInt("type");
                playUrl = bundle.getString("reviewUrl");
                crearPlayer(playUrl);
            } else if (msg.what == CHANGE_CHANNEL) {
                if (liveList != null && index >= 0) {
                    MainChanel.Lives listBean = liveList.get(index);
                    if (sourcesList != null & sourcesList.size() > 0) {
                        playUrl = sourcesList.get(0);
                    }
                    if (playUrl != null) {
                        crearPlayer(playUrl);
                        int id = listBean.getId();
                        writeChannelId(id);
                        mPlayerPresneter.loadVodItem(id);
                    }
                }
            } else if (msg.what == DESTORY_MEDIA) {
                if (mVideoView != null) {
                    try {
                        mVideoView.release();
                        mVideoView = null;
                    } catch (Exception e) {
                        Log.d("creatPlayer", "creatPlayer==>:" + e);
                    }
                }
            }
        }
    };

    private void playLive(MainChanel.Lives liveListBean) {
        sourcesList = liveListBean.getSources();
        index = liveList.indexOf(liveListBean);
        playUrl = sourcesList.get(0);
        crearPlayer(playUrl);
        writeChannelId(liveListBean.getId());
        live_play_later.setText("");
        live_current_text.setText("");
        time_play_later.setText("");
        time_current_text.setText("");
        seekLayout.setVisibility(View.INVISIBLE);
        Current_Type = LIVE_TYPE;
        mPlayerPresneter.loadVodItem(liveListBean.getId());
    }

    public void writeChannelId(int id) {
        SharedPreferences.Editor editor = sharePreferences.edit();
        editor.putInt("id", id);
        editor.commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mVideoView != null) {
            mVideoView.pause();
            mVideoView.release();
            mVideoView = null;
        }
        unregisterReceiver(receiver);
    }

    @Override
    public void finish() {
        super.finish();
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (type == LIVE_TYPE) {
                if (intent != null) {
                    int type = intent.getIntExtra("type", 0);
                    if (type == COLLECTION) {
                        CacheDataPresenter.getPresenter(PlayerActivity.this).saveLiveProgram(mProgram);
                    }
                }
            }
        }
    };

}
